package com.iwords.android;


import org.apache.commons.lang.StringEscapeUtils;

import com.iwords.android.R;

import android.graphics.Typeface;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.view.ViewGroup.LayoutParams;

/** 用于组织翻页显示单词和例句的视图。 */
public class AnimationView{
	private static final String SENTENCES_URL = "file:///android_asset/word.html";
	static class ViewGroup {
		View animation_layout;
		TextView spelling;
		TextView phonetics;
		TextView countdown;
		TextView meaning;
		ImageButton readingButton;
		ScrollView sentencesScroll;
		WebView sentences;
		int flag;
		public void clearView(WebView newSentences){
			
			//System.out.println("AnimationView.clearView()............................");
			//System.out.println("AnimationView.ViewGroup.clearView() sentences = "+sentences+"------------------------------");
			if(sentences!=null){
				sentences.stopLoading();
				sentences.clearView();
			}
			//System.out.println("AnimationView.ViewGroup.clearView().removeViewAt(0)------------------------------");
			sentencesScroll.removeAllViews();
			sentences = newSentences;
			readingButton.setVisibility(View.INVISIBLE);
			spelling.setText("");
			phonetics.setText("");
			meaning.setText("");
			countdown.setText("");
		}
	}
	
	private ShowWord showWord;
	private WordIllustration wordIllustration;
	private WordStatus word;
	
	private ViewGroup current;
	private ViewGroup offscreen;
	
	public AnimationView(ShowWord showWord) {
		//System.out.println("com.iwords.android.AnimationView() !!!!!!!!!!!!!!!!!!!");
		this.showWord = showWord;

		Typeface font = Typeface.createFromAsset(showWord.getAssets(), "SEGOEUI.TTF");

		ViewGroup group1 = new ViewGroup();
		group1.animation_layout = (View) find(R.id.animation_layout);
		group1.spelling = ((TextView) find(R.id.spelling));
		group1.phonetics = ((TextView) find(R.id.phonetics));
		group1.phonetics.setTypeface(font);
		group1.meaning = (TextView) find(R.id.meaning);
		group1.sentencesScroll = (ScrollView)find(R.id.sentences_scroll);
		//group1.sentences = this.createWebView();
		group1.countdown = (TextView) find(R.id.counter_down);
		group1.readingButton = (ImageButton) find(R.id.reading_button);
		//group1.readingButton.setOnClickListener(new ReadingButtonListener());
		group1.readingButton.setOnTouchListener(new ReadingButtonListener2());
		group1.flag = 1;
		offscreen = group1;
		//groupsQueue.addLast(group1);

		ViewGroup group2 = new ViewGroup();
		group2.animation_layout = (View) find(R.id.animation_layout2);
		group2.spelling = ((TextView) find(R.id.spelling2));
		group2.phonetics = ((TextView) find(R.id.phonetics2));
		group2.phonetics.setTypeface(font);
		group2.meaning = (TextView) find(R.id.meaning2);
		group2.sentencesScroll = (ScrollView)find(R.id.sentences2_scroll);
		//group2.sentences = this.createWebView();
		group2.countdown = (TextView) find(R.id.counter_down2);
		group2.readingButton = (ImageButton) find(R.id.reading_button2);
		//group2.readingButton.setOnClickListener(new ReadingButtonListener());
		group2.readingButton.setOnTouchListener(new ReadingButtonListener2());
		group2.flag = 2;
		current = group2;
		//groupsQueue.addLast(group2);
	}
	
	private WebView createWebView(){
		//System.out.println("AnimationView.createWebView() 000000000------------------------------");
		WebView webView = new WebView(showWord);
		
		webView.setVerticalScrollBarEnabled(true);
		//webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		webView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		WebSettings webSettings = webView.getSettings();  	
		webSettings.setJavaScriptEnabled(true);  
		webSettings.setSaveFormData(false);  
		webSettings.setSavePassword(false);  
		webSettings.setSupportZoom(false);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		//myjs是自己定义的，供javascript访问的接口  
		// this is necessary for "alert()" to work  
		webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onConsoleMessage(String message, int lineNumber,String sourceID) {
                //System.out.println("MyApplication : "+ message + " -- From line "+ lineNumber + " of " + sourceID);
                super.onConsoleMessage(message, lineNumber, sourceID);
            }
		}); 
		webView.setOnTouchListener(showWord);//滑动事件监听注册
		webView.addJavascriptInterface(this, "javaForJS");
		webView.loadUrl(SENTENCES_URL);
		return webView;
	}
	
	public void display(){
		//System.out.println("AnimationView.display()");
		//System.out.println("AnimationView.display() current.spelling.getText() = "+current.spelling.getText());
		//System.out.println("AnimationView.display() offscreen.spelling.getText() = "+offscreen.spelling.getText());
		current.phonetics.setVisibility(View.VISIBLE);
		current.meaning.setVisibility(View.VISIBLE);
		current.sentencesScroll.addView(current.sentences);
	}
	
	public WordIllustration getWordIllustration() {
		return wordIllustration;
	}

	public void setWordIllustration(WordIllustration wordIllustration) {
		this.wordIllustration = wordIllustration;
	}

	private View find(int id) {
		return showWord.findViewById(id);
	}
	/**
	 * 用于两种场景，1是程序启动，显示第一个单词。 2是用户切换单词队列，显示队列中的第一个单词。
	 * 两种情况下都不需要动画效果，因为动画效果的移动方向是有意义表示的。但是两种情况下都需要清除，
	 * 当前显示的view中的内容。
	 */
	void showWord(WordStatus word) {
		//System.out.println("************************AnimationView.showWord() ");
		//if(word!=null){
			//System.out.println("AnimationView.showWord() word = "+word.getSpelling());
		//}else{
			//System.out.println("AnimationView.showWord() word = "+word);
		//}
		try {
			//if(this.word!=null){
			//System.out.println("AnimationView.showWord() current.clearView()------------------------------");
			current.clearView(this.createWebView());//考虑将clearView改为生成新的webView，替换现有WebView
			//}
			this.word = word;
			if(word == null) return;
			String spelling = word.getSpelling() + " ";
			String phonetics = (word.getPhonetics()==null?"":word.getPhonetics());
			String meaning = word.getMeaning();
			current.readingButton.setVisibility(View.INVISIBLE);
			current.spelling.setText(StringEscapeUtils.unescapeHtml(spelling));
			current.phonetics.setText(StringEscapeUtils.unescapeHtml(phonetics));
			current.phonetics.setVisibility(View.INVISIBLE);
			current.meaning.setText(meaning);
			current.meaning.setVisibility(View.INVISIBLE);
			//System.out.println("AnimationView.showWord() $$$$$$$$$$$$ current ViewGroup viewGroup.flag="+current.flag+" spelling="+spelling);
			//System.out.println("AnimationView.showWord() $$$$$$$$$$$$ current ViewGroup current.sentences="+current.sentences);
			countdown(word, current);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	ShowWordCountdown counter;
	/**
	 * 当频繁切换不同级别单词队列或快速翻页单词，会启动多个counter，
	 * 处理一下。
	 */
	private void countdown(WordStatus word, ViewGroup group) {
		int time = 3000;
		try{
			time = 1000*((IWordsApp) showWord.getApplicationContext()).getUserSettings().getInt("countdown");
			//System.out.println("@@@@@@@@@@@@@@@@@@@单词朗读倒计时读秒：time = "+time);
		}catch(Exception e){}
		counter = new ShowWordCountdown(time, 200, word, group, this, showWord);
		counter.start();
	}

	/**
	 * 动画时，topview保持不变，新单词在bottom view中显示，然后动画到视野
	 */
	void showWordAnimating(WordStatus word) {
		//if(word!=null){
		//	System.out.println("AnimationView.showWordAnimating() word = "+word.getSpelling());
		//}else{
		//	System.out.println("AnimationView.showWordAnimating() word = "+word);
		//}
		try {
			//交换current和offscreen
			ViewGroup temp = current;
			current = offscreen;
			offscreen = temp;
			//填写当前词汇显示内容
			showWord(word);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	void animate(AnimationDirection direction, WordStatus word) {
		// 两组ViewComponents轮换显示
		showWordAnimating(word);
		//groupsQueue.addFirst(groupsQueue.removeLast());
		switch (direction) {
			case Up: {
				animate(R.anim.slide_out_up, R.anim.slide_in_down);
				break;
			}
			case Down: {
				animate(R.anim.slide_out_down, R.anim.slide_in_up);
				break;
			}
			case Left: {
				animate(R.anim.slide_out_left, R.anim.slide_in_right);
				break;
			}
			case Right: {
				animate(R.anim.slide_out_right, R.anim.slide_in_left);
				break;
			}
		}
	}

	/** 轮换单词时的动画。 */
	private void animate(int animOut, int animIn) {
		View out = offscreen.animation_layout;
		Animation animationOut = AnimationUtils.loadAnimation(showWord, animOut);
		animationOut.setAnimationListener(new DisplayNextAnimation(animIn));
		out.startAnimation(animationOut);
	}

	/**
	 * 用于在单词显示动画Layout移除时，启动第二个动画。
	 **/
	private final class DisplayNextAnimation implements
			Animation.AnimationListener {
		private final int animIn;

		private DisplayNextAnimation(int animIn) {
			this.animIn = animIn;
		}

		public void onAnimationStart(Animation animation) {
			//System.out.println("DisplayNextAnimation.onAnimationStart()");
			//final View inView = top().animation_layout;
			final View inView = current.animation_layout;
			inView.bringToFront();
			inView.post(new Runnable() {
				public void run() {
					Animation animation = AnimationUtils.loadAnimation(
							showWord, animIn);
					inView.startAnimation(animation);
				}
			});
		}

		public void onAnimationEnd(Animation animation) {
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}
	public void googleTTS(final int index){
		vibrate();
		String en = this.getWordIllustration().getSentences().get(index).en;
		String href1="http://translate.google.com/translate_tts?tl=en&q=";
		href1 = href1 + CodeUtils.encode(en.replaceAll("<b>", "").replaceAll("</b>", ""));
		IWordsMediaPlayer.getInstance().play(href1);
	}
	
	/**WordKnownLevel点击事件监听器
	class ReadingButtonListener implements View.OnClickListener{
	    public void onClick(View v) {
	    	//System.out.println("AnimationView.ReadingButtonListener.onclick()!!!!!!!!!");
	    	if(word == null) return;
	    	
	    	IWordsMediaPlayer.getInstance().read(word, showWord.getResources().getString(R.string.voice));
	    }
	}*/
	
	class ReadingButtonListener2 implements View.OnTouchListener{
		public boolean onTouch(View v, MotionEvent event) {
			if(word == null) return true;
			if(event.getAction() == MotionEvent.ACTION_DOWN) {
				vibrate();
				((ImageButton)v).setImageDrawable(showWord.getResources().getDrawable(R.drawable.speaker_icon_down));
			}else if(event.getAction() == MotionEvent.ACTION_UP){
				((ImageButton)v).setImageDrawable(showWord.getResources().getDrawable(R.drawable.speaker_icon));		
				IWordsMediaPlayer.getInstance().read(word, showWord.getResources().getString(R.string.voice));
			}
			return true;
		}
	}
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)showWord.getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}

}